package com.ry.widget;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 *
 * 矩形进度条
 *
 * Create by renxianzuo on 2021/1/7
 * Describe
 */
public class MyHorizontalProgressBar extends RelativeLayout {
    private Paint mPaint;//画笔
    private Paint mLinePaint;
    private int mFillColor;//填充颜色
    private int mBgColor;//背景颜色
    private boolean isNoCircle;
    private int mPercent = 0;//已转化为0至100范围的当前进度，随动画时间改变而改变
    private int MAX = 10000;
    private int mBorderColor = Color.rgb(0xD3,0xD3,0xD3);

    private RectF rectF = new RectF();
    private float radius =  100;

    public MyHorizontalProgressBar(Context context) {
        super(context);
    }

    @SuppressLint("Recycle")
    public MyHorizontalProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint(context);
    }

    public MyHorizontalProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context);
    }

    public MyHorizontalProgressBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initPaint(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();

        //裁剪圆角矩形
        Path path = new Path();
        rectF.set(getPaddingLeft(), getPaddingTop(), getWidth()-getPaddingRight(), getHeight()-getPaddingBottom());
        path.addRoundRect(rectF, new float[]{radius,radius,radius,radius,radius,radius,radius,radius}, Path.Direction.CW);
        canvas.clipPath(path);

        //绘制进度条外边框
        mPaint.setStyle(Paint.Style.STROKE);
        rectF.set(getPaddingLeft(), getPaddingTop(), getWidth()-getPaddingRight(), getHeight()-getPaddingBottom());
        canvas.drawRoundRect(rectF, radius, radius, mLinePaint);


        mPaint.setColor(mBgColor);
        mPaint.setStyle(Paint.Style.FILL);
        rectF.set(getPaddingLeft(), getPaddingTop(), getWidth()-getPaddingRight(), getHeight()-getPaddingBottom());
        canvas.drawRoundRect(rectF, radius, radius, mPaint);

        //填充内部进度
        mPaint.setPathEffect(null);
        mPaint.setColor(mFillColor);
        mPaint.setStyle(Paint.Style.FILL);
        //内部进度填充长度，随动画时间改变而改变
        float percent = mPercent * 1f / MAX;
        rectF.set(getPaddingLeft(), getPaddingTop(), getPaddingLeft()+(getWidth()-getPaddingLeft() - getPaddingRight())*percent, getHeight()-getPaddingBottom());
        if (isNoCircle) {//设置右边是直角
//            canvas.saveLayer(rectF, mPaint);
            canvas.drawRect(rectF, mPaint);
//            canvas.drawRoundRect(rectF, radius, radius, mPaint);
//            canvas.saveLayer(rectF, mPaint);
        } else {
            canvas.drawRoundRect(rectF, radius, radius, mPaint);
        }
//        canvas.drawText(String.valueOf(percent),50f,50f, mPaint);
        canvas.restore();
        super.onDraw(canvas);
    }

    private void initPaint(Context context) {
        setWillNotDraw(false);

        mPaint = new Paint();
        mLinePaint = new Paint();

        mLinePaint.setColor(Color.parseColor("#D3D3D3"));
        mLinePaint.setStyle(Paint.Style.STROKE);
        mLinePaint.setStrokeWidth(dipToPx(context,1));
        mLinePaint.setAntiAlias(true);

        mPaint.setColor(mBgColor);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
    }

    /**
     * 设置背景颜色
     *
     * @param bgColor
     */
    public void setBackgroundColor(int bgColor) {
        mBgColor = bgColor;
        invalidate();
    }

    /**
     * 设置边框颜色
     * @param borderColor
     */
    public void setBorderColor(int borderColor){
        this.mBorderColor = borderColor;
        invalidate();
    }

    /**
     * 设置背景圆角大小
     *
     * @param radius
     */
    public void setRadius(int radius){
        this.radius = radius;
        invalidate();
    }

    /**
     * 设置进度条填充颜色和进度
     *
     * @param progress      进度条实时值
     * @param maxProgress   进度条最大值
     * @param progressColor 进度条颜色
     * @param isNoCircle    true代表右边没有圆角
     */
    public void setProgress(int progress, int maxProgress, int progressColor, boolean isNoCircle) {
        this.isNoCircle = isNoCircle;
        mFillColor = progressColor;
        int percent = progress * MAX / maxProgress;//得出当前progress占最大进度值百分比（0-100）
        if (percent < 0) {
            percent = 0;
        }
        if (percent > MAX) {
            percent = MAX;
        }
        ValueAnimator animator = ValueAnimator.ofInt(0, percent);
        animator.setDuration(1000);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mPercent = (int) valueAnimator.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();
    }

    /**
     * 设置进度条填充颜色和进度
     *
     * @param progress      进度条实时值
     * @param maxProgress   进度条最大值
     * @param progressColor 进度条颜色
     * @param isNoCircle    true代表右边没有圆角
     * @param duration 动画时长
     */
    public void setProgress(int progress, int maxProgress, int progressColor, boolean isNoCircle, int duration) {
        this.isNoCircle = isNoCircle;
        mFillColor = progressColor;
        int percent = progress * MAX / maxProgress;//得出当前progress占最大进度值百分比（0-100）
        if (percent < 0) {
            percent = 0;
        }
        if (percent > MAX) {
            percent = MAX;
        }
        final int curProgress = percent;
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(duration*1000);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mPercent =  (int)((Float)valueAnimator.getAnimatedValue() * curProgress);
                invalidate();
            }
        });
        animator.start();
    }

    /**
     * dp转px
     *
     * @param context context
     * @param dpValue dp
     * @return px
     */
    private static int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
